package offerbook;

/**
 * 把字符串转为int类型。注意string可以带 +，-
 * @date 2020/3/11 21:59
 */
public class Code49_IntegerParseInt {
    int UP_BOUND = Integer.MAX_VALUE % 10 ; // 7
    int LOW_BOUND = Integer.MIN_VALUE % 10 ; // -8
    int UP_RES = Integer.MAX_VALUE / 10;
    int LOW_RES = Integer.MIN_VALUE / 10;
    public  int StrToInt(String str) {
        if(str == null || str.length() == 0) return 0;
        int positive = 1; //1代表+，-1代表-
        int res = 0;
        int index = 0;
        //默认是10进制
        int radix = 10;
        //处理第一位是否是+,-
        if(!(str.charAt(0) >= '0' && str.charAt(0) <='9')){
            if(str.charAt(0) == '+'){
                if(str.length() <= 1) return 0;
            }else if(str.charAt(0) == '-'){
                if(str.length() <= 1) return 0;
                positive = -1;
            }else {//非法字符
                return 0;
            }
            //+ or -
            index++;
        }
        while (index < str.length()){
            //判断当前位是否合法
            if(!legal(str,index)) return 0;
            //判断是否溢出
            if (isOverflow(res,positive,str,index)) return 0;
            //否则相加,positive为 +,-代表正负
            res = res * radix + positive*(str.charAt(index) - '0');
            index++;
        }
        return res;
    }
    private boolean legal(String str,int index){
        return str.charAt(index) >= '0' && str.charAt(index) <='9';
    }
    private  boolean isOverflow(int res, int positive, String str, int index) {
        int last = str.charAt(index) - '0';
        if(positive == 1){
            if(res > UP_RES || res == UP_RES && last > UP_BOUND){
                return true;
            }
        }else {
            //negative
            last = -last;
            if(res < LOW_RES || res == LOW_RES && last < LOW_BOUND){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Code49_IntegerParseInt tools = new Code49_IntegerParseInt();
        //
        System.out.println(Integer.MIN_VALUE);
        System.out.println(tools.StrToInt("-123"));
        System.out.println(tools.StrToInt("+123"));
        System.out.println(tools.StrToInt("+123a"));
        System.out.println(tools.StrToInt(Integer.MAX_VALUE+""));
        System.out.println(tools.StrToInt(Integer.MIN_VALUE+""));
        System.out.println(tools.StrToInt("-2147483649"));

    }
}
